<template>
	<view class="content">
		<view class="form-container">
			<uni-forms :model="form" ref="uForm" :rules="rules" label-position="top" validate-trigger="submit">
				<uni-forms-item label="楼层号" name="floor_number" required>
					<uni-easyinput v-model="form.floor_number" placeholder="请输入楼层号" type="number" />
				</uni-forms-item>
				
				<uni-forms-item label="楼层描述" name="description">
					<uni-easyinput type="textarea" v-model="form.description" placeholder="请输入楼层描述（选填）" :autoHeight="true" />
				</uni-forms-item>
			</uni-forms>
			
			<view class="submit-btn">
				<u-button type="primary" text="添加楼层" @click="submitForm"></u-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue';
	
	// 表单数据
	const form = reactive({
		floor_number: '',
		description: ''
	});
	
	// 表单校验规则
	const rules = {
		floor_number: {
			rules: [
				{ required: true, errorMessage: '请输入楼层号' },
				{ pattern: /^\d+$/, errorMessage: '楼层号必须为数字' }
			]
		}
	};
	
	const uForm = ref(null);
	const token = ref(''); // 定义token变量
	
	// 生命周期
	onMounted(() => {
		getToken(); // 获取token
	});
	
	// 获取token
	const getToken = () => {
		token.value = uni.getStorageSync('uni_id_token') || '';
	};
	
	// 提交表单
	const submitForm = () => {
		if (!uForm.value) {
			console.error('表单引用不存在');
			uni.showToast({
				title: '表单验证失败',
				icon: 'none'
			});
			return;
		}
		
		uForm.value.validate().then(async res => {
			uni.showLoading({
				title: '添加中'
			});
			try {
				const floor_number = parseInt(form.floor_number);
				
				// 确保token是最新的
				getToken();
				
				if (!token.value) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				
				const res = await uniCloud.callFunction({
					name: 'add-floor',
					data: {
						floor_number,
						description: form.description,
                        token: token.value,
					},
					getAuthInfo: true // 自动传递用户token给云函数
				});
				
				if (res.result.code === 0) {
					uni.showToast({
						title: '楼层添加成功',
						icon: 'success'
					});
					
					// 重置表单
					form.floor_number = '';
					form.description = '';
					
					// 延迟返回
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.result.message,
						icon: 'none'
					});
				}
			} catch (e) {
				console.error('添加楼层失败', e);
				uni.showToast({
					title: '添加楼层失败',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		}).catch(err => {
			console.log('表单验证失败', err);
		});
	};
</script>

<style lang="scss" scoped>
	.content {
		padding: 20px;
	}
	
	.form-container {
		background-color: #ffffff;
		border-radius: 10px;
		padding: 20px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}
	
	.submit-btn {
		margin-top: 30px;
	}
</style> 